from django.conf import settings
from jwt import decode
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.request import HttpRequest

from apps.user.models import User


class JWTAuthenticate(BaseAuthentication):

    def authenticate(self, request: HttpRequest) -> (User, str):
        if 'swagger' in request.path_info:
            return
        token = request.headers.get('Access-Token')
        if not token:
            raise AuthenticationFailed('用户未登录')
        payload = decode(token, key=settings.SECRET_KEY)
        id = payload.get('id')
        user = User.objects.filter(id=id).first()
        if not user:
            raise AuthenticationFailed('验证错误')
        return user, token
        pass
